<template>
  <div class="login">
    <van-nav-bar
      title="登录"
      class="page-nav-bar"
    >
      <template #left>
        <van-icon color="#fff" name="cross" @click="goback" />
      </template>
    </van-nav-bar>

    <van-form ref="form" @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        name="mobile"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请输入手机号' },
          {pattern:/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,message: '请输入正确的手机号'}
        ]"
      >
        <template #left-icon>
          <i class="toutiao toutiao-shouji" />
        </template>
      </van-field>

      <van-field
        v-model="form.code"
        type="password"
        name="code"
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请输入验证码' },
          {pattern:/^[0-9]{6}$/,message: '请输入正确的验证码'}
        ]"
      >
        <template #left-icon>
          <i class="toutiao toutiao-yanzhengma" />
        </template>
        <template #button>
          <van-count-down v-if="isShow" :time="6 * 10000" format="sss" @finish="isShow = false" />
          <van-button v-else native-type="button" class="btn" size="small" type="primary" @click="onSend">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button class="login-btn" round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { getCode } from '@/api/user.js'
import { login } from '@/api/user.js'

import { Toast } from 'vant'
export default {
  data() {
    return {
      form: {
        mobile: '',
        code: ''
      },
      isShow: false
    }
  },

  created() {

  },

  methods: {
    async onSubmit() {
      try {
        const res = await login({
          mobile: this.form.mobile,
          code: this.form.code
        })
        this.$store.commit('initUser', res)
        this.$router.push('/profile')
      } catch (err) {
        Toast.fail('sb')
      }
    },
    async onSend() {
      try {
        await this.$refs.form.validate('mobile')
        await getCode(this.form.mobile)
        Toast.success('success')
        this.isShow = true
        // console.log(123)
      } catch (err) {
        // console.log(err)
        if (!err.response) return
        if (err.response.status === 429) {
          return Toast.fail('sb')
        }
        Toast.fail('sb')
      }
    },
    goback() {
      this.$router.push('/profile')
    }
  }
}
</script>

<style scoped lang='less'>
.login-btn{
  width: 694px;
  height: 88px;
  background: #6DB4FB;
  border-radius: 10px;
  border: 0px;
}
.toutiao{
  font-size: 37px;
}
.btn{
  padding: 0;
  width: 152px;
  height: 46px;
  border-radius: 23px;
  border: 0;
  background: #EDEDED;
  font-size: 22px;
  color: #666;
}
</style>
